package actions;

import java.sql.SQLException;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;
import forms.DegreeForm;
import forms.StudentForm;
import model.UniversityModel;

public class DegreeLocationAction extends Action {

	private static final boolean DEBUG = true;
	//private static final int UNKNOWN = -1;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws DbException {
		
		// get degree location from degree form
		DegreeForm dform = (DegreeForm)form;
		String location = dform.getLocation();
		
		if (DEBUG) {
			System.err.println("DegreeLocationAction: saving location(" + location +")");
		}
		
		// save degree location into session
		request.getSession().setAttribute("location", location);
		
		// store DegreeForm into session
		dform = new DegreeForm();
		
		dform.setLocation(location);
		request.getSession().setAttribute("dform", dform);
		
		// put list of universities into a vector
		RowSet rset = UniversityModel.getUniversity(location);

		Vector<String> universities_1 = new Vector<String>();
		Vector<String> universities_2 = new Vector<String>();
		Vector<String> universities_3 = new Vector<String>();

		int count = 0;
		
		try {
			while (rset.next()) {
				
				count = (count + 1)%3;
				
				switch(count) {
					case 1:
						universities_1.add(rset.getString("university"));
						break;
					case 2:
						universities_2.add(rset.getString("university"));
						break;
					default:
						universities_3.add(rset.getString("university"));
						break;
				}
			}
			
			if (universities_2.size() < universities_1.size()) {
				universities_2.add("");
			}
			
			if (universities_3.size() < universities_1.size()) {
				universities_3.add("");
			}
		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
		}
		
		request.setAttribute("universities_1", universities_1);
		request.setAttribute("universities_2", universities_2);
		request.setAttribute("universities_3", universities_3);
		
		return mapping.findForward("success");
	}
	
}
